//
//  HZGoodsSalesViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/26.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZGoodsSalesViewController.h"
#import "HZMallGoodsTemaiListViewController.h"
#import "HZMallGoodsListViewController.h"
#import "HZGoodsDetailViewController.h"

//view
#import "HZMallHttpManager.h"

@interface HZGoodsSalesViewController()<UIWebViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) UIButton *backBtn;

@end

@implementation HZGoodsSalesViewController

- (void) viewDidLoad {
    [super viewDidLoad];
    
    if (self.hiddenNavigationItem) {
        self.navigationController.navigationBar.hidden = YES;
        //backBtn
        self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn.frame = CGRectMake(SCREEN_WIDTH - 80, 13, 70, 25);
        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        self.backBtn.layer.cornerRadius = 2;
        self.backBtn.layer.borderColor = [UIColor redColor].CGColor;
        self.backBtn.titleLabel.font = JKAppGlobleFontSmallTagText;
        self.backBtn.layer.borderWidth = UP(1);
        [self.backBtn setTitle:@"返回主页" forState:UIControlStateNormal];
        [self.backBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.backBtn addTarget:self action:@selector(backBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    } else {
        self.navigationController.navigationBar.hidden = NO;
        self.navigationController.navigationBar.translucent = YES;
        //backBtn
        self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                                [self.ubo ow:40 oh:40])];
        [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.backBtn addTarget:self action:@selector(backBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = HZ_WHITE_COLOR;
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP oy:self.navigationAndStatusBarHeight], [self.ubo fw:UB_WIDTH fh:UB_HEIGHT oh:-self.navigationAndStatusBarHeight])];
    self.webView.delegate = self;
    self.webView.scrollView.delegate = self;
    
//    self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
//    self.webView.scrollView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.webView.scrollView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.webView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.webView viewController:self tryAgain:@selector(refreshData)];
    
    [self.view addSubview:self.webView];
    
    if (self.hiddenNavigationItem) {
        [self.webView.scrollView addSubview:self.backBtn];
    }
    
    [self.webView.nothingRefreshView show];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webURL]]];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (self.hiddenNavigationItem) {
        self.navigationController.navigationBar.hidden = YES;
    } else {
        self.navigationController.navigationBar.hidden = NO;
    }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.translucent = YES;
    
    self.webView.frame = CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP oy:self.navigationAndStatusBarHeight], [self.ubo fw:UB_WIDTH fh:UB_HEIGHT oh:-self.navigationAndStatusBarHeight]);
    
    if (self.webTitle.length) {
        self.title = self.webTitle;
    }else{
        self.title = @"活动";
    }
}

#pragma mark 返回
- (void)backBtnOnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 从新加载页面
- (void)refreshData{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webURL]]];
}

#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *requestString = [[[request URL]  absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"requestString:%@",requestString);
    NSString *protocolString = @"http://localhost/";
    if ([requestString hasPrefix:protocolString]) {
        
        [webView stopLoading];
        
        requestString = [requestString substringFromIndex:protocolString.length];
        NSRange range = [requestString rangeOfString:@"?c="];
        NSString *path = [requestString substringToIndex:range.location];
        requestString = [requestString substringFromIndex:range.location+range.length];
        range = [requestString rangeOfString:@"&d="];
        
        NSString *callback = range.location == 0 ? @"":[requestString substringToIndex:range.location];
        
        NSString *jsonString = [requestString substringFromIndex:range.location+range.length];
        
        
        NSDictionary *jsonDict = [jsonString objectFromJSONString];
        
        
        //do something
        
        NSString *data = @"";
        
        
        //do something
        
        if ([path isEqualToString:kMallLocalPathTypeCategory]) {
            //跳到分类页面category:分类   {}
            
            self.tabBarController.selectedIndex = 1;
            [self.navigationController popToRootViewControllerAnimated:NO];
        }else if([path isEqualToString:kMallLocalPathTypeDetail]){
            //跳到商品详情页面detail:商品详情   {activities_id:10,shop_id:10,product_id:10}
            
            if ([jsonDict count]) {
                HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
                detailVC.shopID = [jsonDict stringForKey:APIKEY_mall_shop_id nilValue:@""];
                detailVC.productID = [jsonDict stringForKey:APIKEY_mall_product_id nilValue:@""];
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            }
            
        }else if([path isEqualToString:kMallLocalPathTypeList]){
            //跳到商品列表页面list:商品列表         {activities_id:100,name:''}
            if ([jsonDict count]) {
                
                HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
                mallGoodsListVC.actID = [jsonDict stringForKey:@"activities_id" nilValue:@"-1"];
                if (![mallGoodsListVC.actID isEqualToString:@"-1"]) {
                    mallGoodsListVC.actName = [jsonDict stringForKey:APIKEY_mall_name nilValue:@"分类"];
                    mallGoodsListVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:mallGoodsListVC animated:YES];
                }
            }
            
        }else if([path isEqualToString:kMallLocalPathTypeWeb]){
            //跳到web页面 web:{url:'',name:''}
            if ([jsonDict count]) {
                HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
                salesVC.webTitle = [jsonDict stringForKey:APIKEY_mall_name nilValue:@""];
                salesVC.webURL = [jsonDict stringForKey:APIKEY_mall_url nilValue:@""];
                salesVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:salesVC animated:YES];
            }
            
        }else if([path isEqualToString:kMallLocalPathTypeTimeSale]){
            //跳到特卖商品列表页面list:特卖商品列表         {activities_id:100,name:''}
            if ([jsonDict count]) {
                
                HZMallGoodsTemaiListViewController *temaiGoodsListVC = [[HZMallGoodsTemaiListViewController alloc] init];
                temaiGoodsListVC.actID = [jsonDict stringForKey:@"activities_id" nilValue:@"-1"];
                if (![temaiGoodsListVC.actID isEqualToString:@"-1"]) {
                    temaiGoodsListVC.actName = [jsonDict stringForKey:APIKEY_mall_name nilValue:@"限时特卖"];
                    temaiGoodsListVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:temaiGoodsListVC animated:YES];
                }
            }

        }
        
        
        [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"kangxihui_callback('%@','%@',%@)", callback, path, data]];
    }
    
    
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.webView.scrollView endRefreshingAll];
    [self.webView.nothingRefreshView remove];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self.webView.nothingRefreshView activeStop];
}

@end
